'''
Created on Aug 17, 2010

@author: riche

Graciously stolen from Dive Into Python:
http://diveintopython.org/functional_programming/all_together.html

Modified to work with Python 3 conventions

'''
import unittest, os, re, sys

def mod_to_path(mod_name):
    '''Given a mod name in . notation return a proper path with /'''
    return mod_name.replace('.', '/')

def regression_test():
    '''
    Runs all tests in a given sub module. If no argument given, runs tests
    in the current directory.
    '''   
    path = os.path.abspath(os.path.dirname(sys.argv[0]))
    index = 1
    if len(sys.argv) > 1:
        if sys.argv[1] == '-v':
            index = 2
    if len(sys.argv) > 1:
        path = path + '/' + mod_to_path(sys.argv[index])
    try:
        files = os.listdir(path)
    except OSError as err:
        print(err)
        quit()
    test = re.compile("_test\.py$", re.IGNORECASE)      
    files = [file for file in files if test.search(file)]
    filenameToModuleName = lambda f: os.path.splitext(f)[0]
    if len(sys.argv) > 1:
        moduleNames = ['ft.tests.{}.{}'.format(sys.argv[index],filenameToModuleName(file)) for file in files]
    else: 
        moduleNames = ['ft.tests.{}'.format(filenameToModuleName(file)) for file in files]
    for mod_name in moduleNames:
        __import__(mod_name)   
    modules = [sys.modules[mod_name] for mod_name in moduleNames]
    #print(modules)                 
    load = unittest.defaultTestLoader.loadTestsFromModule
    return unittest.TestSuite([load(module) for module in modules])   

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == '-v':
            unittest.main(defaultTest='regression_test', argv=sys.argv[0:2])
    unittest.main(defaultTest='regression_test', argv=[sys.argv[0]])